package com.example.hlddz2.repository;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CartRepository {
    private static final String SP_NAME = "cart_sp";
    private static final String KEY_CART = "key_cart";

    public static class CartItem {
        public int goodsId;
        public String name;
        public double price;
        public String image;
        public int count;
    }

    private static CartRepository instance;
    public static synchronized CartRepository getInstance(Context context) {
        if (instance == null) instance = new CartRepository(context.getApplicationContext());
        return instance;
    }

    private final SharedPreferences sp;
    private final Gson gson = new Gson();
    private final MutableLiveData<List<CartItem>> cartLive = new MutableLiveData<>();

    private CartRepository(Context ctx) {
        sp = ctx.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        cartLive.setValue(load());
    }

    public LiveData<List<CartItem>> getCart() {
        return cartLive;
    }

    public void add(CartItem item) {
        List<CartItem> list = new ArrayList<>(cartLive.getValue() == null ? new ArrayList<>() : cartLive.getValue());
        boolean merged = false;
        for (CartItem it : list) {
            if (it.goodsId == item.goodsId) {
                it.count += item.count;
                merged = true;
                break;
            }
        }
        if (!merged) list.add(item);
        saveAndPost(list);
    }

    public void remove(int goodsId) {
        List<CartItem> list = new ArrayList<>(cartLive.getValue() == null ? new ArrayList<>() : cartLive.getValue());
        Iterator<CartItem> it = list.iterator();
        while (it.hasNext()) {
            if (it.next().goodsId == goodsId) it.remove();
        }
        saveAndPost(list);
    }

    public void updateCount(int goodsId, int count) {
        List<CartItem> list = new ArrayList<>(cartLive.getValue() == null ? new ArrayList<>() : cartLive.getValue());
        for (CartItem it : list) {
            if (it.goodsId == goodsId) {
                it.count = Math.max(1, count);
                break;
            }
        }
        saveAndPost(list);
    }

    public double calcTotal() {
        double sum = 0;
        List<CartItem> list = cartLive.getValue();
        if (list != null) {
            for (CartItem it : list) sum += it.price * it.count;
        }
        return sum;
    }

    public void clear() {
        saveAndPost(new ArrayList<>());
    }

    private void saveAndPost(List<CartItem> list) {
        sp.edit().putString(KEY_CART, gson.toJson(list)).apply();
        cartLive.postValue(list);
    }

    private List<CartItem> load() {
        String json = sp.getString(KEY_CART, "");
        if (json == null || json.isEmpty()) return new ArrayList<>();
        Type type = new TypeToken<List<CartItem>>(){}.getType();
        List<CartItem> list = gson.fromJson(json, type);
        return list == null ? new ArrayList<>() : list;
    }
}


